<template>
	<view>
		<TopNav title="邀请海报" bg-color="#fff"></TopNav>
		<canvas canvas-id="posterCanvas" class="full-width"
			:style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}"></canvas>
		<view class="flex justify-center fixed-bottom p-lr16">
			<view class="self-btn flex flex-direction full-width" hover-class="pressed" @click="handleSaveToAlbum">
				<text class="f-s16 line-height22">保存海报</text>
			</view>
		</view>
		<Toast></Toast>
	</view>
</template>

<script>
	import {invitationQrcode} from "@/api/reward"
	export default {
		data() {
			return {
				canvasWidth: 375, // 海报宽度，单位px
				canvasHeight: 636, // 海报高度，单位px
				posterPath: '', // 生成的海报路径
				qrCodePath: '/static/logo.png', // 二维码路径
				posterBgPath: '/static/images/reward/poster-3.png' // 海报背景图路径
			}
		},
		onReady() {
			// 获取屏幕宽度
			const systemInfo = uni.getSystemInfoSync()
			this.canvasWidth = systemInfo.windowWidth
			// 计算图片高度（原图375*636）
			this.canvasHeight = Math.round(this.canvasWidth * (636 / this.canvasWidth))
			this.getQrcode()
			
		},
		methods: {
			getQrcode(){
				invitationQrcode().then(res=>{
					this.qrCodePath = res.data
					setTimeout(() => {
						this.generatePoster()
					}, 200)
				})
			},
			// 生成海报
			generatePoster() {

				const ctx = uni.createCanvasContext('posterCanvas', this);

				// 1. 绘制背景图
				ctx.drawImage(this.posterBgPath, 0, 0, this.canvasWidth, this.canvasHeight);

				// 2. 绘制二维码到指定位置（示例坐标为(500, 1000)，大小为200x200）
				const qrCodeSize = 100;
				const qrCodeX = 20;
				const qrCodeY = 500;

				ctx.drawImage(this.qrCodePath, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);

				// 绘制完成
				ctx.draw(false, () => {
					setTimeout(() => {
						this.canvasToTempFilePath();
					}, 300);
				});
			},

			// 将Canvas转为临时文件路径
			canvasToTempFilePath() {
				uni.canvasToTempFilePath({
					canvasId: 'posterCanvas',
					success: (res) => {
						this.posterPath = res.tempFilePath;
						uni.hideLoading();
					},
					fail: (err) => {
						this.$toast('海报加载失败，请稍后重试')
					}
				}, this);
			},

			// 保存到相册
			handleSaveToAlbum() {
				this.$modal.loading('正在保存').then(() => {
					uni.saveImageToPhotosAlbum({
						filePath: this.posterPath,
						success: () => {
							this.$modal.closeLoading()
							this.$toast('已保存到相册')
						},
						fail: (err) => {
							this.$modal.closeLoading()
							// 处理用户拒绝授权的情况
							if (err.errMsg.includes('auth deny')) {
								uni.showModal({
									title: '提示',
									content: '需要相册权限才能保存图片',
									confirmText: '前往设置',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting();
										}
									}
								});
							} else {
								this.$toast('保存失败')
							}
						}
					});
				})


			}
		}
	}
</script>

<style scoped lang="scss">
	@import '@/common/css/var.scss';

	page {
		@include fixed-bottom;
	}
</style>